// 主应用文件 - 包含初始化和事件处理

import { STATE, StateManager } from './state.js';
import { CommonUtils } from './utils.js';
import { UIManager } from './ui.js';
import { BettingManager } from './betting.js';
import { BankerManager } from './banker.js';
import { rulesConfig, animalConfig, tailConfig, oddsConfig } from './config.js';

// 应用管理器
export const AppManager = {
    // 初始化应用
    init() {
        this.setupLotteryTabs();
        this.setupGameTabs();
        this.setupSubTabs();
        this.setupNumberGrid();
        this.setupAnimalGrid();
        this.setupTailGrid();
        this.forceTailOddsUpdate(); // 强制更新尾数赔率
        this.setupSideButtons();
        this.setupBanboButtons();
        this.setupZongxiaoButtons();
        this.setupSeboButtons();
        this.setupBettingList();
        this.setupModal();
        this.setupViewSwitch();
        this.setupTestButtons();
        this.updateBettingRules();
        this.updateContentPanels();
        BankerManager.init();
        
        // 设置默认视图为投注界面
        this.switchView('betting');
        
        // 数字竞猜分析平台初始化完成
    },

    // 设置彩票类型页签
    setupLotteryTabs() {
        const lotteryTabs = document.querySelectorAll('.lottery-tab');
        
        lotteryTabs.forEach(tab => {
            tab.addEventListener('click', function() {
                UIManager.switchTab(lotteryTabs, this, 'data-lottery', (dataValue) => {
                    StateManager.setCurrentLottery(dataValue);
                    AppManager.updateLotteryInfo();
                });
            });
        });
    },

    // 设置玩法页签
    setupGameTabs() {
        const gameTabs = document.querySelectorAll('.game-tab');
        
        gameTabs.forEach(tab => {
            tab.addEventListener('click', function() {
                UIManager.switchTab(gameTabs, this, 'data-game', (dataValue) => {
                    StateManager.setCurrentGame(dataValue);
                    AppManager.updateSubTabs();
                    AppManager.resetSubGame();
                    AppManager.updateBettingRules();
                    AppManager.updateContentPanels();
                });
            });
        });
    },

    // 设置子玩法页签
    setupSubTabs() {
        const subTabs = document.querySelectorAll('.sub-tab');
        
        subTabs.forEach(tab => {
            tab.addEventListener('click', function() {
                const parentTabs = this.closest('.sub-tabs').querySelectorAll('.sub-tab');
                
                UIManager.switchTab(parentTabs, this, 'data-sub', (dataValue) => {
                    StateManager.setCurrentSub(dataValue);
                    AppManager.updateBettingRules();
                    AppManager.updateContentPanels();
                    AppManager.updateAnimalOdds(); // 更新生肖赔率显示
                    AppManager.updateTailOdds(); // 更新尾数赔率显示
                    UIManager.clearAllSelections();
                });
            });
        });
    },

    // 更新子页签显示
    updateSubTabs() {
        const allSubTabs = document.querySelectorAll('.sub-tabs');
        allSubTabs.forEach(tabs => tabs.classList.remove('active'));
        
        const currentSubTabs = document.querySelector(`.${STATE.currentGame}-tabs`);
        if (currentSubTabs) {
            currentSubTabs.classList.add('active');
        }
    },

    // 重置子玩法
    resetSubGame() {
        const currentSubTabs = document.querySelector(`.${STATE.currentGame}-tabs`);
        if (currentSubTabs) {
            const firstTab = currentSubTabs.querySelector('.sub-tab');
            if (firstTab) {
                // 移除所有活动状态
                currentSubTabs.querySelectorAll('.sub-tab').forEach(t => t.classList.remove('active'));
                
                // 激活第一个
                firstTab.classList.add('active');
                StateManager.setCurrentSub(firstTab.getAttribute('data-sub'));
            }
        }
    },

    // 设置号码网格
    setupNumberGrid() {
        this.generateNumberGrid();
        
        // 为号码按钮添加事件监听
        document.addEventListener('click', function(e) {
            if (e.target.classList.contains('number-btn') && e.target.hasAttribute('data-number')) {
                BettingManager.handleNumberClick(e.target);
            }
        });
    },

    // 生成号码网格
    generateNumberGrid() {
        const numberGrids = document.querySelectorAll('.number-grid');
        
        numberGrids.forEach(grid => {
            grid.innerHTML = '';
            
            for (let i = 1; i <= 49; i++) {
                const button = document.createElement('button');
                button.className = `number-btn ${CommonUtils.getNumberColor(i)}`;
                button.setAttribute('data-number', i);
                button.textContent = i.toString().padStart(2, '0');
                grid.appendChild(button);
            }
        });
    },

    // 设置生肖网格
    setupAnimalGrid() {
        this.generateAnimalGrid();
        
        // 为生肖按钮添加事件监听
        document.addEventListener('click', function(e) {
            if (e.target.classList.contains('animal-btn') && e.target.hasAttribute('data-animal')) {
                BettingManager.handleAnimalClick(e.target);
            }
        });
    },

    // 生成生肖网格
    generateAnimalGrid() {
        const animalGrids = document.querySelectorAll('.animal-grid');
        
        animalGrids.forEach(grid => {
            grid.innerHTML = '';
            
            animalConfig.animals.forEach(animal => {
                const button = document.createElement('button');
                button.className = 'animal-btn';
                if (animal.isBenming) {
                    button.classList.add('benming');
                }
                button.setAttribute('data-animal', animal.id);
                
                // 创建生肖按钮内容
                const nameDiv = document.createElement('div');
                nameDiv.className = 'animal-name';
                nameDiv.textContent = animal.name;
                
                const numbersDiv = document.createElement('div');
                numbersDiv.className = 'animal-numbers';
                numbersDiv.textContent = animal.numbers.map(n => n.toString().padStart(2, '0')).join(' ');
                
                const oddsDiv = document.createElement('div');
                oddsDiv.className = 'animal-odds';
                // 赔率会根据当前子玩法动态设置
                
                button.appendChild(nameDiv);
                button.appendChild(numbersDiv);
                button.appendChild(oddsDiv);
                
                grid.appendChild(button);
            });
        });
        
        // 更新生肖按钮的赔率显示
        this.updateAnimalOdds();
    },

    // 更新生肖按钮的赔率显示
    updateAnimalOdds() {
        const animalBtns = document.querySelectorAll('.animal-btn');
        const currentSub = STATE.currentSub;
        
        animalBtns.forEach(btn => {
            const animalId = btn.getAttribute('data-animal');
            const animal = animalConfig.getAnimalById(animalId);
            const oddsDiv = btn.querySelector('.animal-odds');
            
            if (oddsDiv && animal) {
                let odds = '';
                switch (currentSub) {
                    case 'texiao':
                        odds = animal.isBenming ? '赔率9.500' : '赔率11.100';
                        break;
                    case 'yixiao':
                        odds = animal.isBenming ? '赔率1.779' : '赔率2.090';
                        break;
                    case 'zhengxiao':
                        odds = animal.isBenming ? '赔率1.633' : '赔率1.959';
                        break;
                    default:
                        odds = ''; // 其他玩法不显示单个生肖赔率
                        break;
                }
                oddsDiv.textContent = odds;
            }
        });
    },

    // 设置两面投注按钮
    setupSideButtons() {
        document.addEventListener('click', function(e) {
            if (e.target.closest('.side-btn')) {
                BettingManager.handleSideButtonClick(e.target.closest('.side-btn'));
            }
        });
    },

    // 设置半波投注按钮
    setupBanboButtons() {
        document.addEventListener('click', function(e) {
                    if (e.target.closest('.banbo-btn-detailed')) {
            BettingManager.handleBanboButtonClick(e.target.closest('.banbo-btn-detailed'));
                BettingManager.updateBanboSelectionInfo();
            }
        });
    },

    // 设置总肖按钮
    setupZongxiaoButtons() {
        document.addEventListener('click', function(e) {
            if (e.target.closest('.zongxiao-btn')) {
                BettingManager.handleZongxiaoButtonClick(e.target.closest('.zongxiao-btn'));
            }
        });
    },

    // 设置色波按钮
    setupSeboButtons() {
        document.addEventListener('click', function(e) {
            if (e.target.closest('.sebo-btn')) {
                BettingManager.handleSeboButtonClick(e.target.closest('.sebo-btn'));
            }
        });
    },

    // 设置投注清单
    setupBettingList() {
        // 确认选择按钮 - 支持所有确认按钮
        document.addEventListener('click', function(e) {
            if (e.target.classList.contains('confirm-selection-btn')) {
                if (e.target.id === 'banboConfirmBtn') {
                    BettingManager.confirmBanboSelection();
                } else if (e.target.id && e.target.id.includes('xiao')) {
                    // 生肖相关的确认按钮
                    BettingManager.confirmAnimalSelection();
                } else if (e.target.id && (e.target.id.includes('wei') || e.target.id.includes('tail'))) {
                    // 尾数相关的确认按钮
                    BettingManager.confirmTailSelection();
                } else if (e.target.id && e.target.id.includes('buzhong')) {
                    // 不中相关的确认按钮
                    BettingManager.confirmBuzhongSelection();
                } else if (e.target.id && e.target.id.includes('sebo')) {
                    // 色波相关的确认按钮
                    BettingManager.confirmSeboSelection();
                } else {
                    BettingManager.confirmNumberSelection();
                }
            }
        });

        // 清空选择按钮
        document.addEventListener('click', function(e) {
            if (e.target.id === 'clearSelectionBtn') {
                BettingManager.clearNumberSelection();
            }
        });

        // 立即投注按钮
        document.addEventListener('click', function(e) {
            if (e.target.id === 'submitBetBtn') {
                BettingManager.showConfirmModal();
            }
        });

        // 投注清单事件委托
        const betItems = document.getElementById('betItems');
        if (betItems) {
            // 防抖处理赔率和金额输入
            const debouncedUpdate = this.debounce(function(input) {
                if (input.classList.contains('bet-amount')) {
                    BettingManager.updateBetAmount(input);
                } else if (input.classList.contains('bet-odds')) {
                    BettingManager.updateBetOdds(input);
                }
            }, 300);

            betItems.addEventListener('input', function(e) {
                if (e.target.classList.contains('bet-amount') || e.target.classList.contains('bet-odds')) {
                    debouncedUpdate(e.target);
                }
            });

            betItems.addEventListener('click', function(e) {
                console.log('投注清单点击事件:', e.target);
                console.log('目标元素类名:', e.target.className);
                console.log('是否是删除按钮:', e.target.classList.contains('delete-bet'));
                console.log('是否是赔率历史按钮:', e.target.classList.contains('odds-history-btn'));
                
                if (e.target.classList.contains('delete-bet')) {
                    console.log('调用删除功能');
                    BettingManager.deleteBetItem(e.target);
                } else if (e.target.classList.contains('odds-history-btn')) {
                    console.log('调用赔率历史功能');
                    UIManager.showOddsHistoryDropdown(e.target);
                }
            });
        }
        
        // 刷新潜在赔付按钮事件
        const refreshBtn = document.getElementById('refreshPotentialWinsBtn');
        if (refreshBtn) {
            refreshBtn.addEventListener('click', function() {
                console.log('刷新按钮被点击');
                console.log('BettingManager:', BettingManager);
                console.log('refreshAllPotentialWins方法:', BettingManager.refreshAllPotentialWins);
                
                if (BettingManager && typeof BettingManager.refreshAllPotentialWins === 'function') {
                    BettingManager.refreshAllPotentialWins();
                } else {
                    console.error('BettingManager.refreshAllPotentialWins 不是一个函数');
                }
            });
        }
    },

    // 防抖函数
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    },

    // 设置模态框
    setupModal() {
        // 确认投注弹窗
        const confirmModal = document.getElementById('confirmModal');
        if (confirmModal) {
            // 确定按钮
            const confirmBtn = confirmModal.querySelector('.confirm-btn');
            if (confirmBtn) {
                confirmBtn.addEventListener('click', function() {
                    BettingManager.submitBets();
                });
            }

            // 取消按钮
            const cancelBtn = confirmModal.querySelector('.cancel-btn');
            if (cancelBtn) {
                cancelBtn.addEventListener('click', function() {
                    BettingManager.hideConfirmModal();
                });
            }

            // 点击遮罩关闭
            confirmModal.addEventListener('click', function(e) {
                if (e.target === confirmModal) {
                    BettingManager.hideConfirmModal();
                }
            });
        }
    },

    // 设置视图切换
    setupViewSwitch() {
        // 投注界面按钮
        const bettingViewBtn = document.getElementById('bettingViewBtn');
        if (bettingViewBtn) {
            bettingViewBtn.addEventListener('click', function() {
                AppManager.switchView('betting');
            });
        }

        // 坐庄系统按钮
        const bankerViewBtn = document.getElementById('bankerViewBtn');
        if (bankerViewBtn) {
            bankerViewBtn.addEventListener('click', function() {
                AppManager.switchView('banker');
            });
        }
    },

    // 设置测试按钮
    setupTestButtons() {
        // 生成测试数据按钮
        const generateTestDataBtn = document.getElementById('generateTestDataBtn');
        if (generateTestDataBtn) {
            generateTestDataBtn.addEventListener('click', function() {
                BankerManager.generateTestData();
            });
        }
        
        // 快速测试按钮
        const quickTestBtn = document.getElementById('quickTestBtn');
        if (quickTestBtn) {
            quickTestBtn.addEventListener('click', function() {
                BankerManager.quickTestLossRanking();
            });
        }
    },

    // 切换视图
    switchView(view) {
        // 切换视图
        
        // 更新按钮状态
        const bettingViewBtn = document.getElementById('bettingViewBtn');
        const bankerViewBtn = document.getElementById('bankerViewBtn');
        
        if (bettingViewBtn && bankerViewBtn) {
            bettingViewBtn.classList.toggle('active', view === 'betting');
            bankerViewBtn.classList.toggle('active', view === 'banker');
        }

        // 更新body的CSS类来控制界面显示
        document.body.classList.toggle('banker-view', view === 'banker');

        // 获取投注相关的导航元素
        const gameNav = document.querySelector('.game-nav');
        const subNav = document.querySelector('.sub-nav');
        const bettingInfo = document.getElementById('bettingInfo');
        const bettingContent = document.getElementById('bettingContent');
        const bankerContent = document.getElementById('bankerContent');

        if (view === 'betting') {
            // 显示投注界面
            if (gameNav) gameNav.style.display = 'block';
            if (subNav) subNav.style.display = 'block';
            if (bettingInfo) bettingInfo.style.display = 'block';
            if (bettingContent) bettingContent.style.display = 'block';
            if (bankerContent) bankerContent.style.display = 'none';
        } else if (view === 'banker') {
            // 显示坐庄系统界面，隐藏投注相关元素
            if (gameNav) gameNav.style.display = 'none';
            if (subNav) subNav.style.display = 'none';
            if (bettingInfo) bettingInfo.style.display = 'none';
            if (bettingContent) bettingContent.style.display = 'none';
            if (bankerContent) bankerContent.style.display = 'block';
            
            // 更新坐庄系统数据显示，会自动生成亏损排序
            BankerManager.updateDisplay();
        }
    },

    // 更新投注规则
    updateBettingRules() {
        const rulesElement = document.getElementById('bettingRules');
        if (rulesElement) {
            const rules = CommonUtils.getCurrentRules();
            rulesElement.innerHTML = rules;
        }
    },

    // 更新内容面板
    updateContentPanels() {
        const panelKey = `${STATE.currentGame}-${STATE.currentSub}`;
        UIManager.switchPanel(panelKey);
    },

    // 更新彩票信息
    updateLotteryInfo() {
        console.log('切换到彩票类型:', STATE.currentLottery);
    },

    // 设置尾数网格
    setupTailGrid() {
        this.generateTailGrid();
        
        // 为尾数按钮添加事件监听
        document.addEventListener('click', function(e) {
            if (e.target.classList.contains('tail-btn') && e.target.hasAttribute('data-tail')) {
                BettingManager.handleTailClick(e.target);
            }
        });
    },

    // 生成尾数网格
    generateTailGrid() {
        // 直接调用更新赔率函数，使用正确的赔率配置
        this.updateTailOdds();
    },

    // 更新尾数按钮的赔率显示
    updateTailOdds() {
        const currentSub = STATE.currentSub;
        
        if (currentSub === 'tematowei') {
            // 特码头尾：使用图片中的正确赔率
            const headBtns = document.querySelectorAll('[data-tail-type="head"]');
            const tailBtns = document.querySelectorAll('[data-tail-type="tail"]');
            
            headBtns.forEach(btn => {
                const headValue = parseInt(btn.getAttribute('data-tail'));
                const oddsSpan = btn.querySelector('.tail-odds');
                if (oddsSpan && !isNaN(headValue)) {
                    const headOdds = oddsConfig.weishu.tematowei.head[headValue];
                    oddsSpan.textContent = `赔率${headOdds}`;
                }
            });
            
            tailBtns.forEach(btn => {
                const tailValue = parseInt(btn.getAttribute('data-tail'));
                const oddsSpan = btn.querySelector('.tail-odds');
                if (oddsSpan && !isNaN(tailValue)) {
                    const tailOdds = oddsConfig.weishu.tematowei.tail[tailValue];
                    oddsSpan.textContent = `赔率${tailOdds}`;
                }
            });
        } else {
            // 其他尾数玩法
            const tailBtns = document.querySelectorAll('.tail-btn:not([data-tail-type])');
            
            tailBtns.forEach(btn => {
                const oddsSpan = btn.querySelector('.tail-odds');
                if (oddsSpan) {
                    let odds = '';
                    switch (currentSub) {
                        case 'erweilian':
                            // 二尾连显示两种赔率
                            const tailValue = btn.getAttribute('data-tail');
                            if (tailValue === '0') {
                                odds = `含0尾:${oddsConfig.weishu.erweilian.withZero}`;
                            } else {
                                odds = `不含0尾:${oddsConfig.weishu.erweilian.withoutZero}`;
                            }
                            break;
                        case 'sanweilian':
                            // 三尾连显示两种赔率
                            const tailValue3 = btn.getAttribute('data-tail');
                            if (tailValue3 === '0') {
                                odds = `含0尾:${oddsConfig.weishu.sanweilian.withZero}`;
                            } else {
                                odds = `不含0尾:${oddsConfig.weishu.sanweilian.withoutZero}`;
                            }
                            break;
                        case 'siweilian':
                            // 四尾连显示两种赔率
                            const tailValue4 = btn.getAttribute('data-tail');
                            if (tailValue4 === '0') {
                                odds = `含0尾:${oddsConfig.weishu.siweilian.withZero}`;
                            } else {
                                odds = `不含0尾:${oddsConfig.weishu.siweilian.withoutZero}`;
                            }
                            break;
                        case 'zhengteweishu':
                            // 正特尾数显示两种赔率
                            const tailValueZheng = btn.getAttribute('data-tail');
                            if (tailValueZheng === '0') {
                                odds = `含0尾:${oddsConfig.weishu.zhengteweishu.withZero}`;
                            } else {
                                odds = `不含0尾:${oddsConfig.weishu.zhengteweishu.withoutZero}`;
                            }
                            break;
                        default:
                            odds = '赔率1.500';
                            break;
                    }
                    oddsSpan.textContent = odds;
                }
            });
        }
    },

    // 强制更新尾数赔率（确保显示正确）
    forceTailOddsUpdate() {
        // 强制更新特码头尾的赔率
        setTimeout(() => {
            const headBtns = document.querySelectorAll('[data-tail-type="head"]');
            const tailBtns = document.querySelectorAll('[data-tail-type="tail"]');
            
            headBtns.forEach(btn => {
                const headValue = parseInt(btn.getAttribute('data-tail'));
                const oddsSpan = btn.querySelector('.tail-odds');
                if (oddsSpan && !isNaN(headValue)) {
                    const headOdds = oddsConfig.weishu.tematowei.head[headValue];
                    oddsSpan.textContent = `赔率${headOdds}`;
                }
            });
            
            tailBtns.forEach(btn => {
                const tailValue = parseInt(btn.getAttribute('data-tail'));
                const oddsSpan = btn.querySelector('.tail-odds');
                if (oddsSpan && !isNaN(tailValue)) {
                    const tailOdds = oddsConfig.weishu.tematowei.tail[tailValue];
                    oddsSpan.textContent = `赔率${tailOdds}`;
                }
            });
            
            // 强制更新尾数赔率完成
        }, 100);
    }
};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    AppManager.init();
});

// 将BettingManager暴露到全局，以便HTML中的onclick可以访问
window.BettingManager = BettingManager;